import router from '@/router'
import { useUserStore } from '@/stores/user'
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) =>
  {
    // 添加认证token
    const userStore = useUserStore()
    const token = userStore.token
    if (token)
    {
      config.headers.Authorization = `Bearer ${token}`
    }

    // 添加请求时间戳（防止缓存）
    if (config.method === 'get')
    {
      config.params = {
        ...config.params,
        _t: Date.now()
      }
    }

    return config
  },
  (error) =>
  {
    console.error('请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) =>
  {
    const { data } = response

    // 检查业务状态码
    if (data.code !== undefined)
    {
      if (data.code === 200)
      {
        return response
      } else if (data.code === 401)
      {
        // 未授权，清除用户信息并跳转登录
        const userStore = useUserStore()
        userStore.logout()
        router.push('/login')
        ElMessage.error('登录已过期，请重新登录')
        return Promise.reject(new Error('Unauthorized'))
      } else
      {
        // 其他业务错误
        const message = data.message || '请求失败'
        ElMessage.error(message)
        return Promise.reject(new Error(message))
      }
    }

    return response
  },
  (error) =>
  {
    console.error('响应拦截器错误:', error)

    // 网络错误处理
    if (!error.response)
    {
      ElMessage.error('网络连接失败，请检查网络设置')
      return Promise.reject(error)
    }

    const { status, data } = error.response

    switch (status)
    {
      case 400:
        ElMessage.error(data?.message || '请求参数错误')
        break
      case 401:
        // 未授权
        const userStore = useUserStore()
        userStore.logout()
        router.push('/login')
        ElMessage.error('登录已过期，请重新登录')
        break
      case 403:
        ElMessage.error('访问被拒绝，权限不足')
        break
      case 404:
        ElMessage.error('请求的资源不存在')
        break
      case 422:
        ElMessage.error(data?.message || '数据验证失败')
        break
      case 429:
        ElMessage.error('请求过于频繁，请稍后再试')
        break
      case 500:
        ElMessage.error('服务器内部错误')
        break
      case 502:
        ElMessage.error('网关错误')
        break
      case 503:
        ElMessage.error('服务暂时不可用')
        break
      case 504:
        ElMessage.error('网关超时')
        break
      default:
        ElMessage.error(data?.message || `请求失败 (${status})`)
    }

    return Promise.reject(error)
  }
)

// API方法封装
const request = {
  // GET请求
  get(url, params = {}, config = {})
  {
    return api.get(url, { params, ...config })
  },

  // POST请求
  post(url, data = {}, config = {})
  {
    return api.post(url, data, config)
  },

  // PUT请求
  put(url, data = {}, config = {})
  {
    return api.put(url, data, config)
  },

  // PATCH请求
  patch(url, data = {}, config = {})
  {
    return api.patch(url, data, config)
  },

  // DELETE请求
  delete(url, config = {})
  {
    return api.delete(url, config)
  },

  // 文件上传
  upload(url, formData, onProgress = null)
  {
    return api.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: onProgress
    })
  },

  // 文件下载
  download(url, params = {}, filename = null)
  {
    return api.get(url, {
      params,
      responseType: 'blob'
    }).then(response =>
    {
      const blob = new Blob([response.data])
      const downloadUrl = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = downloadUrl

      // 尝试从响应头获取文件名
      const contentDisposition = response.headers['content-disposition']
      if (contentDisposition && !filename)
      {
        const match = contentDisposition.match(/filename="?([^"]+)"?/)
        if (match)
        {
          filename = match[1]
        }
      }

      link.download = filename || 'download'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(downloadUrl)

      return response
    })
  }
}

// 具体API接口
export const userAPI = {
  // 用户登录
  login(credentials)
  {
    return request.post('/auth/login', credentials)
  },

  // 用户注册
  register(userData)
  {
    return request.post('/auth/register', userData)
  },

  // 获取用户信息
  getUserInfo()
  {
    return request.get('/user/info')
  },

  // 更新用户信息
  updateUserInfo(userInfo)
  {
    return request.put('/user/info', userInfo)
  },

  // 修改密码
  changePassword(passwordData)
  {
    return request.post('/user/change-password', passwordData)
  },

  // 用户登出
  logout()
  {
    return request.post('/auth/logout')
  },

  // 刷新token
  refreshToken()
  {
    return request.post('/auth/refresh')
  }
}

export const softwareAPI = {
  // 获取软件列表
  getSoftwareList(params = {})
  {
    return request.get('/software', params)
  },

  // 搜索软件
  searchSoftware(keyword, params = {})
  {
    return request.get('/software/search', { keyword, ...params })
  },

  // 根据分类获取软件
  getSoftwareByCategory(category, params = {})
  {
    return request.get(`/software/category/${category}`, params)
  },

  // 获取软件详情
  getSoftwareDetail(id)
  {
    return request.get(`/software/${id}`)
  },

  // 获取热门软件
  getPopularSoftware(limit = 10)
  {
    return request.get('/software/popular', { limit })
  },

  // 获取最新软件
  getLatestSoftware(limit = 10)
  {
    return request.get('/software/latest', { limit })
  },

  // 获取软件统计信息
  getSoftwareStats()
  {
    return request.get('/software/stats')
  },

  // 增加软件下载次数
  incrementDownloadCount(id)
  {
    return request.post(`/software/${id}/download`)
  },

  // 增加软件查看次数
  incrementViewCount(id)
  {
    return request.post(`/software/${id}/view`)
  }
}

export const scriptAPI = {
  // 生成安装脚本
  generateScript(scriptData)
  {
    return request.post('/script/generate', scriptData)
  },

  // 获取脚本模板
  getScriptTemplate(os)
  {
    return request.get(`/script/template/${os}`)
  },

  // 验证脚本配置
  validateScriptConfig(config)
  {
    return request.post('/script/validate', config)
  }
}

export const systemAPI = {
  // 获取系统信息
  getSystemInfo()
  {
    return request.get('/system/info')
  },

  // 获取镜像源列表
  getMirrorSources()
  {
    return request.get('/system/mirrors')
  },

  // 检查更新
  checkUpdate()
  {
    return request.get('/system/update')
  },

  // 获取配置信息
  getConfig()
  {
    return request.get('/system/config')
  }
}

// 导出默认实例和具体API
export default api
export { request }
